package com.kingsoft.dc.khaos.extender.meta.impl;

import com.alibaba.fastjson.JSON;
import com.kingsoft.dc.khaos.extender.exception.MetaException;
import com.kingsoft.dc.khaos.extender.meta.api.DmApiUtils;
import com.kingsoft.dc.khaos.extender.meta.api.DmAuthResult;
import com.kingsoft.dc.khaos.extender.meta.api.DmRequest;
import com.kingsoft.dc.khaos.extender.meta.model.AuthTable;
import com.kingsoft.dc.khaos.extender.meta.model.MetaParams;
import com.kingsoft.dc.khaos.extender.meta.model.TableAuthParams;
import com.kingsoft.dc.khaos.extender.meta.model.auth.AuthDetailInfo;
import com.kingsoft.dc.khaos.extender.meta.model.auth.DmAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * create by goosoog 2019/6/27.
 */
public class DmAuthImpl implements RelationAuth {
    private static Logger logger = LoggerFactory.getLogger(DmAuthImpl.class);
    /**
     * 检查用户权限
     * @param request
     * @return
     */
    public DmAuth getProjectAuth(DmRequest request) {
        MetaParams metaParams = request.getMetaParams();
        TableAuthParams authParams = new TableAuthParams();
        List<AuthTable> arr = new ArrayList<>();
        AuthTable authTable = new AuthTable();
        authTable.setDbName(metaParams.getDbName());
        authTable.setTblName(metaParams.getTblName());
        authTable.setPrivSet(metaParams.getPrivSet().toArray(new String[metaParams.getPrivSet().size()]));
        arr.add(authTable);
        request.setTableAuthParams(authParams.buildAuthParams(metaParams.getEnv(), metaParams.getJobProjectId(), metaParams.getJobProjectName(), metaParams.getDsId(), metaParams.getDsName(), arr));
        return getProjectAuthDetail(request);
//        boolean checkResutlt = false ;
//        DmAuth userAuth = DmApiUtils.getProjectAuth(request);
//        return userAuth;
    }

    /**
     * 获取权限校验详情
     * @param request
     * @return
     */
    public static DmAuth getProjectAuthDetail(DmRequest request) {
        //userAuth获取的的值不为200，直接走了else（getProjectAuthDetail没有获取到）
        DmAuthResult userAuth = DmApiUtils.getProjectAuthDetail(request);
        DmAuth dmAuth = new DmAuth();
        if (userAuth.getStatus() == 200) {
            dmAuth.setTotalPrivs(userAuth.isTotalPrivs());
            if (!userAuth.isTotalPrivs()) {
                AuthDetailInfo detailInfo = JSON.parseObject(userAuth.getResult(), AuthDetailInfo.class);
                dmAuth.setAuthDetailInfo(detailInfo);
                TableAuthParams authParams = request.getTableAuthParams();
                logger.error("此项目没有足够权限访问数据表,数据源:[{}],数据表:[{}.{}],被拒绝的权限:[{}]", authParams.getDsName(), detailInfo.getDbName(), detailInfo.getTableName(), detailInfo.formatDetailInfo());
            } else {
                logger.info("鉴权成功,结果为通过");
            }
            return dmAuth;
        } else {
            logger.error("库权限异常");
            String message = userAuth != null ? userAuth.getMessage():"";
            logger.error("鉴权失败,原因:{}", message);
            throw new MetaException("权限接口返回数据异常,message:" + message);
        }
    }
}
